package org.deng.learn.concurrent.basic;

import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;

/**
 * @ Author: DengLibin
 * @ Description:
 * @ DateTime:  22:27 2018/5/7 0007
 */
public class ConcurrentMapDemo {


    //100个线程， 每个线程往map中插入10000个数，完成后计算耗时
    public static void main(String[] args){
        //Map<String,String> map = new Hashtable<>();//线程安全 加了锁的 374ms
        //Map<String,String> map = new ConcurrentHashMap<>(); //并发容器 257ms
        Map<String,String> map = new ConcurrentSkipListMap<>(); //并发容器 跳表 会排序 321ms
        Thread[] threads = new Thread[100];
        Random random = new Random();
        CountDownLatch latch = new CountDownLatch(threads.length);
        for(int i = 0; i < threads.length; i++){
            threads[i] = new Thread(()->{
                for(int a = 0; a < 10000; a++ ){
                    map.put("a"+random.nextInt(100000),"b"+random.nextInt(10000));
                }
                latch.countDown();

            });
        }
        long s = System.currentTimeMillis();
        Arrays.asList(threads).forEach(t->t.start());
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long e = System.currentTimeMillis();
        System.out.println("map大小:"+map.size()+"耗时:"+(e-s));

    }
}
